package personal.xjl._23java1studentdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import personal.xjl._23java1studentdemo.model.Course;
import personal.xjl._23java1studentdemo.model.Student;
import personal.xjl._23java1studentdemo.model.Teacher;
import personal.xjl._23java1studentdemo.service.CourseService;
import personal.xjl._23java1studentdemo.service.TeacherService;

import java.util.List;

@Controller
@RequestMapping("/Teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private CourseService courseService;

    @RequestMapping("list")
    public String list(Model model) {
        List<Teacher> teachers = teacherService.findAll();
        model.addAttribute("teachers", teachers);
        return "listTeachers";
    }

    @RequestMapping("remove")
    public String remove(int id) {
        teacherService.remove(id);
        return "redirect:/Teacher/list/1/3";
    }

    @RequestMapping("add")
    public String add(Teacher teacher, Model model) {
        teacherService.add(teacher);
        return "redirect:/Teacher/list/1/3";
    }

    @RequestMapping("toAdd")
    public String toAdd(Model model) {
        List<Course> courses = courseService.findAll();
        model.addAttribute("courses", courses);
        return "addTeacher";
    }

    @RequestMapping("toPage")
    public String toPage(String page) {
        return page;
    }

    @RequestMapping("toEdit")
    public String toEdit(int id, Model model) {
        Teacher oldTeacher = teacherService.findById(id);
        model.addAttribute("teacher", oldTeacher);
        return "editTeacher";
    }

    @RequestMapping("edit")
    public String edit(Teacher teacher) {
        teacherService.edit(teacher);
        return "redirect:/Teacher/list/1/3";
    }
    //分页显示
    @RequestMapping("list/{currPage}/{pageSize}")
    public String list(Model model, @PathVariable("currPage") int currPage, @PathVariable("pageSize") int pageSize) {
        if (currPage < 1) currPage = 1;
        if (pageSize < 1) pageSize = 5;
        List<Teacher> teachers = teacherService.findByPage(currPage,pageSize);
        model.addAttribute("teachers", teachers);
        return "listTeachers";
    }
}